<?php

namespace app\service;

use share\service\cache\CommonCacheKeyService;
use share\exception\ApiException;
use share\exception\Errno;
use share\service\RedisService;
use share\utils\Helper;

class P2pUpgradeService{

    const P2P_UPGRADE_CACHE_TIMEOUT = 86400;

    public static function getConfByFilter($dn,$sn,$pk){
        $settingData = self::getAllData();
        if(empty($settingData['selector']) || empty($settingData['conf'])){
            throw new ApiException("P2pUpgrade config not set",Errno::COMMON_SYSTEM_CONFIG_NOT_SET);
        }
        foreach($settingData['selector'] as $selector){ 
            if($selector['dn'] && $selector['dn'] != '*'){
                if(strcasecmp($selector['dn'],$dn) !== 0){
                    continue;
                }
            }
            if($selector['sn'] && $selector['sn'] != '*'){
                if(strcasecmp($selector['sn'],$sn) !== 0){
                    continue;
                }
            }
            if($selector['pk'] && $selector['pk'] != '*'){
                if(strcasecmp($selector['pk'],$pk) !== 0){
                    continue;
                }
            }
            $conf = Helper::filterOne($settingData['conf'],['id'=>$selector['p2p_upgrade_conf_id']]);
            if(empty($conf)){
                throw new ApiException("P2pUpgrade conf data lost by p2p_upgrade_conf_id:".$selector['p2p_upgrade_conf_id'],Errno::COMMON_SYSTEM_CONFIG_NOT_SET);
            }
            else{
                return $conf;
            }
        }
        throw new ApiException("P2pUpgrade lost default conf",Errno::COMMON_SYSTEM_CONFIG_NOT_SET);       
    }  

    public static function getAllData(){
        $data = self::getAllByCache();
        return $data;     
    }

    public static function getCacheKey(){
        return CommonCacheKeyService::getCacheKey(CommonCacheKeyService::CACHE_KEY_P2P_UPGRADE);
    }

    public static function getAllByCache(){      
        $cacheKey = self::getCacheKey();
        $data = RedisService::instance(RedisService::CACHE_DB_BASE)->getJson($cacheKey);
        if(!$data){
            $data = self::getAllRawData();
            if($data){
                RedisService::instance(RedisService::CACHE_DB_BASE)->setJson($cacheKey,$data,self::P2P_UPGRADE_CACHE_TIMEOUT);
            }
        }
        return $data;
    }

    /**
     * 删除缓存
     */
    public static function deleteCache(){
        $cacheKey = self::getCacheKey();
        RedisService::instance(RedisService::CACHE_DB_BASE)->del($cacheKey);
    }

    public static function getAllRawData(){
 
        $conf = P2pUpgradeConfService::getNativeAll(null,['id','is_force','start_span','end_span','check_first','check_interval'],'id DESC');
        $selector = P2pUpgradeSelectorService::getNativeAll(null,['id','dn','sn','pk','p2p_upgrade_conf_id','priority'],'priority DESC');
        
        return [
            'conf' => $conf,
            'selector' => $selector,
        ];
    }


}
